<template>
  <el-main>
    <!--    条件查询-->
    <el-form
      ref="searchForm"
      label-width="80px"
      :inline="true"
      size="small"
    >
      <el-form-item>
        <el-input v-model="searchModel.departmentName" placeholder="请输入部门名称"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
        <el-button icon="el-icon-refresh-right" @click="resetValue">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="openAddWindow()" v-if="hasPermission('sys:department:add')">新增</el-button>
      </el-form-item>
    </el-form>
    <!--    数据表格-->
    <!--
    data属性：表格数据
    border属性：是否显示纵向边框
    stripe属性：是否显示斑马线
    default-expand-all属性：是否默认展开所有行
    tree-props属性：设置树形结构相关属性
    row-key属性：行数据的key值
    -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%;margin-bottom: 20px"
      row-key="id"
      default-expand-all
      :tree-props="{children:'children'}"
    >
      <!--      prop属性：指定列显示字段-->
      <!--      label属性：列标题-->
      <el-table-column prop="departmentName" label="班级名称"/>
      <el-table-column prop="parentName" label="所属组织"/>
      <el-table-column prop="phone" label="组织联系方式"/>
      <el-table-column prop="address" label="班级地址"/>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit-outline"
            type="primary"
            size="mini"
            @click="handleEdit(scope.row)"
            v-if="hasPermission('sys:department:edit')"
          >编辑
          </el-button>
          <el-button
            icon="el-icon-delete-solid"
            type="danger"
            size="mini"
            @click="handleDeleteDepartment(scope.row)"
            v-if="hasPermission('sys:department:delete')"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    添加和编辑部门窗口-->
    <system-dialog
      :title="deptDialog.title"
      :visible="deptDialog.visible"
      :width="deptDialog.width"
      :height="deptDialog.height"
      @onClose="onClose()"
      @onConfirm="onConfirm()"
    >
      <div slot="content">
        <el-form :model="dept" ref="deptForm" :rules="rules" label-width="80px" :inline="true" size="small">
          <el-form-item label="所属组织" prop="parentName">
            <el-input v-model="dept.parentName" :readonly="true" @click.native="selectDepartment()"></el-input>
          </el-form-item>
          <el-form-item label="组织名称" prop="departmentName">
            <el-input v-model="dept.departmentName"></el-input>
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="dept.phone"></el-input>
          </el-form-item>
          <el-form-item label="班级地址">
            <el-input v-model="dept.address"></el-input>
          </el-form-item>
          <el-form-item label="序号">
            <el-input v-model="dept.orderNum"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </system-dialog>
    <!--    选择所属部门的窗口-->
    <system-dialog :title="parentDialog.title" :visible="parentDialog.visible" :width="parentDialog.width"
                   :height="parentDialog.height" @onClose="parentOnClose" @onConfirm="parentOnConfirm">
      <div slot="content">
        <el-tree ref="parentTree" :data="treeList" node-key="id" :props="defaultProps" :default-expand-all="true"
                 :highlight-current="true" :expand-on-click-node="false" @node-click="handleNodeClick">
          <div class="customer-tree-node" slot-scope="{node, data}">
            <span v-if="data.children.length===0">
              <i class="el-icon-document"></i>
            </span>
            <span v-else @click="openBtn(data)">
              <svg-icon v-if="data.open" icon-class="add-s"/>
              <svg-icon v-else icon-class="sub-s"/>
            </span>
            <span style="margin-left:5px">{{ node.label }}</span>
          </div>
        </el-tree>
      </div>
    </system-dialog>
  </el-main>
</template>
<script>
//导入department脚本文件
import departmentApi from "@/api/department";
//导入对话框组件
import SystemDialog from "@/components/system/SystemDialog.vue";
import hasPermission from "@/permission/index";

export default {
  name: "department",
  //注册组件
  components: {
    SystemDialog
  },
  data() {
    return {
      searchModel: {
        departmentName: '',//部门名称
      },
      tableData: [],//表格数据
      deptDialog: {
        title: "",//对话框标题
        visible: false,//对话框是否显示
        width: 560,//对话框宽度
        height: 170,//对话框高度
      },
      dept: {
        id: '',//部门id
        departmentName: '',//部门名称
        pid: '',//上级部门id
        parentName: '',//上级部门名称
        phone: '',//部门电话
        address: '',//部门地址
        orderNum: '',//序号
      },
      rules: {
        parentName: [{required: true, trigger: 'change', message: '请选择所属部门'}],
        departmentName: [{required: true, trigger: 'blur', message: '请输入部门名称'}],
      },
      //选择所属部门窗口属性
      parentDialog: {
        title: '选择所属部门',//对话框标题
        visible: false,//对话框是否显示
        width: 300,//对话框宽度
        height: 400,//对话框高度
      },
      //树形菜单列表
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
    };
  },
  //初始化的时候调用
  created() {
    this.search();
  },
  methods: {
    hasPermission,
    /**
     * 查询部门列表
     * @return {Promise<void>}
     */
    async search() {
      //发送查询请求
      let res = await departmentApi.getDepartmentList(this.searchModel);
      //判断是否成功
      if (res.success) {
        // console.log(res);
        this.tableData = res.data;
      }
    },
    /**
     * 重置查询条件
     */
    resetValue(){
      this.searchModel.departmentName = "";//清空表单数据
      this.search();//重新查询
    },
    /**
     * 选择所属部门
     * @return {Promise<void>}
     */
    async selectDepartment() {
      //显示窗口
      this.parentDialog.visible = true;
      //设置窗口标题
      this.parentDialog.title = "选择所属部门";
      //获取部门列表
      let res = await departmentApi.getParentTreeList();
      //判断是否成功
      if (res.success) {
        // console.log(res);
        this.treeList = res.data;
      }
    },
    /**
     * 选择所属部门窗口关闭事件
     */
    parentOnClose() {
      this.parentDialog.visible = false;
    },
    parentOnConfirm() {
      this.parentDialog.visible = false;
    },
    handleNodeClick(data) {
      //当点击树节点时，赋予选中的值
      this.dept.pid = data.id;
      this.dept.parentName = data.departmentName;
    },
    /**
     * 点击树节点+-号折叠展开事件
     * @param data
     */
    openBtn(data) {
      //修改折叠展开状态
      data.open = !data.open;
      this.$refs.parentTree.store.nodesMap[data.id].expanded = data.open;
    },
    /**
     * 打开新增窗口
     */
    openAddWindow() {
      //清空表单数据
      this.$resetForm("deptForm", this.dept);
      //设置对话框标题
      this.deptDialog.title = "新增部门";
      //设置对话框是否显示
      this.deptDialog.visible = true;
    },
    /**
     * 窗口关闭事件
     */
    onClose() {
      //关闭对话框
      this.deptDialog.visible = false;
    },
    /**
     * 窗口确认事件
     */
    onConfirm() {
      //表单验证
      this.$refs.deptForm.validate(async (valid) => {
        //如果验证通过
        if (valid) {
          let res = null;//后端返回的数据
          //判断部门ID是否有数据，如果部门ID为空，则表示新增，否则就是修改
          if (this.dept.id === '') {
            //新增
            //发送新增部门请求
            res = await departmentApi.addDept(this.dept);
          } else {
            //发送修改请求
            res = await departmentApi.updateDept(this.dept);
          }
          //判断是否成功
          if (res.success) {
            this.$message.success(res.message);
            //刷新
            await this.search();
            //关闭窗口
            this.deptDialog.visible = false;
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    /**
     * 编辑部门
     * @param row
     */
    handleEdit(row){
      //数据回显
      this.$objCopy(row,this.dept);
      //设置窗口标题
      this.deptDialog.title = "编辑部门";
      //显示编辑窗口
      this.deptDialog.visible = true;
    },
    /**
     * 删除部门
     * @param row
     * @return {Promise<void>}
     */
    async handleDeleteDepartment(row){
      //查询部门下是否存在子部门
      let result=await departmentApi.checkDepartment({id:row.id});
      // console.log(result)
      //判断是否可以删除
      if (result.success){
        //提示不能删除
        this.$message.warning(result.message);
      }else{
        //确认是否删除
        let confirm=await this.$myconfirm("确认删除该部门吗？");
        if (confirm){
          //发送删除请求
          let res=await departmentApi.deleteDept({id:row.id});
          //判断是否成功
          if (res.success){
            this.$message.success(res.message);
            //刷新
            await this.search();
          }else {
            this.$message.error(res.message);
          }
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-tree {
  .el-tree-node {
    position: relative; //绝对定位
    padding-left: 10px; //左边距
  }

  .el-tree-node__children {
    padding-left: 20px;
  }

  .el-tree-node:last-child:before { //最后一个节点
    height: 40px;
  }

  .el-tree > .el-tree-node:before { //根节点
    border-left: none; //左边框
  }

  .el-tree > .el-tree-node:after { //根节点
    border-top: none; //上边框
  }

  .el-tree-node:before, //根节点
  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .tree:first-child .el-tree-node:before {
    border-left: none;
  }

  .el-tree-node:before {
    border-left: 1px dotted #d9d9d9;
    bottom: 0; //底部
    height: 100%;
    top: -25px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dotted #d9d9d9;
    height: 20px;
    top: 14px;
    width: 24px;
  }

  .el-tree-node__expand-icon.is-leaf {
    width: 8px;
  }

  .el-tree-node__content > .el-tree-node__expand-icon {
    display: none;
  }

  .el-tree-node__content {
    line-height: 30px;
    height: 30px;
    padding-left: 10px !important;
  }
}

::v-deep .el-tree > div {
  &::before {
    display: none;
  }

  &::after {
    display: none;
  }
}
</style>
